package com.example.xlzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xlzx.entity.User;
import com.example.xlzx.dao.UserMapper;
import com.example.xlzx.entity.vo.LoginUserVo;
import com.example.xlzx.entity.vo.LoginVo;
import com.example.xlzx.exception.xlzxException;
import com.example.xlzx.result.ResultCodeEnum;
import com.example.xlzx.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xlzx.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 1
 * @since 2025-03-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public LoginUserVo login(LoginVo loginVo) {
        LoginUserVo loginUserVo = new LoginUserVo();

        LambdaQueryWrapper<User> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(User::getUsername, loginVo.getUsername());
        adminLambdaQueryWrapper.eq(User::getPassword, loginVo.getPassword());
        adminLambdaQueryWrapper.eq(User::getType, loginVo.getType());
        User user = userMapper.selectOne(adminLambdaQueryWrapper);
        if (user == null) {
            throw new xlzxException(ResultCodeEnum.XLZX_ACCOUNT_ERROR);
        }

        String oldToken = redisTemplate.opsForValue().get(String.valueOf(user.getId()));
        if (oldToken != null) {
            // 如果有，强制下线：删除旧的 token
            redisTemplate.delete(String.valueOf(user.getId()));
        }
        String newToken = JwtUtil.createToken(user.getId(), user.getUsername());
        redisTemplate.opsForValue().set(String.valueOf(user.getId()), newToken, 7, TimeUnit.DAYS);
        loginUserVo.setToken(newToken);
        loginUserVo.setUser(user);
        return loginUserVo;

    }

    public Boolean insetUser(User user) {
        User one = (User) ((LambdaQueryChainWrapper) this.lambdaQuery().eq(User::getUsername, user.getUsername())).one();
        if (one != null) {
            throw new xlzxException(ResultCodeEnum.XLZX_ACCOUNT_EXIST_ERROR);
        } else {
            return this.save(user);
        }
    }

    @Transactional
    public Boolean updateUser(User user) {
        return lambdaUpdate()
                .eq(User::getId, user.getId())
                .set(StringUtils.isNotEmpty(user.getUsername()), User::getUsername, user.getUsername())
                .set(StringUtils.isNotEmpty(user.getPassword()), User::getPassword, user.getPassword())
                .set(StringUtils.isNotEmpty(user.getEmail()), User::getEmail, user.getEmail())
                .set(StringUtils.isNotEmpty(user.getPhone()), User::getPhone, user.getPhone())
                .set(StringUtils.isNotEmpty(user.getAvatar()), User::getAvatar, user.getAvatar())
                .set(user.getGender() != null && user.getGender() != 0, User::getGender, user.getGender())
                .set(StringUtils.isNotEmpty(user.getUserRealName()), User::getUserRealName, user.getUserRealName())
                .set(User::getType, user.getType())
                .update();
    }

    public Page<User> selectUser(String userRealName, Integer type, Page<User> pageParam) {
        return lambdaQuery()
                .like(userRealName != null, User::getUserRealName, userRealName)
                .eq(type != null, User::getType, type)
                .page(pageParam);
    }
}
